#include "PlaylistModel.h"
#include "FileItemWidget.h"
#include "BNSPlayerApp.h"
#include "AppData.h"

QWidget *PlaylistItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option);
    QString fileName = index.data(Qt::UserRole + 1).toString();
    double duration = index.data(Qt::UserRole + 2).toDouble();
    auto *editor = new FileItemWidget(fileName, duration, parent);
    return editor;
}

void PlaylistItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    painter->save();

    QString fileName = index.data(Qt::UserRole + 1).toString();
    double duration = index.data(Qt::UserRole + 2).toDouble();

    FileItemWidget tempWidget(fileName, duration);
    tempWidget.resize(option.rect.size());

    QPixmap pixmap(tempWidget.size());
    tempWidget.render(&pixmap);

    painter->drawPixmap(option.rect.topLeft(), pixmap);

    painter->restore();
}

QSize PlaylistItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);

    return QSize(200, 50);  // 自定义项的大小
}

PlaylistModel::PlaylistModel(QObject *parent)
    :: QAbstractListModel(parent)
{

}

QVariant PlaylistModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_playlist.size())
        return QVariant();

    const auto &item = m_playlist.at(index.row());
    switch (role) {
    case Qt::DisplayRole:  // 用于默认显示
        return QString("%1 - %2").arg(item.name, item.duration);
    case FileNameRole:
        return item.name;
    case DurationRole:
        return item.duration;
    default:
        return QVariant();
    }
}
